import {Component, ViewChild} from '@angular/core';
import {
  AlertController,
  IonicPage,
  LoadingController,
  ModalController,
  NavController,
  NavParams,
  Slides,
  ToastController
} from 'ionic-angular';
import {TranslateService} from "@ngx-translate/core";
import {Api} from "../../providers/api/api"
import {Browser} from "../../providers/browser/browser"
import {User} from "../../providers/user/user";

/**
 * Generated class for the HomePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
})
export class HomePage {
  @ViewChild(Slides) slides: Slides;

  kinds: Array<any> = [];
  pages: Array<any> = [];
  currentKind: string = '全部彩种';
  private networkErrorString: string;
  private params: any = {'page': 0, 'size': 60, 'kind': -1};

  constructor(public translateService: TranslateService,
              public navCtrl: NavController,
              public navParams: NavParams,
              public api: Api,
              private alertCtrl: AlertController,
              public user: User,
              public loadingCtrl: LoadingController,
              public toastCtrl: ToastController,
              public modalController: ModalController,
              public alerCtrl: AlertController,
              public browser: Browser) {
    this.loadingCtrl.create({
      content: "数据加载中",
      duration: 500
    }).present();

    this.getKinds();
    this.getPages();
    this.translateService.get('NETWORK_ERROR').subscribe((value) => {
      this.networkErrorString = value;
    });
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad HomePage');
  }

  ionViewDidEnter() {
    this.updateMobile();
  }

  updateMobile() {
    this.user.getUser().then(_user => {
      if (!_user.type && (_user.mobile == null) || _user.mobile == '') {  //非代理
        let alert = this.alertCtrl.create({
          message: '请完善手机号,方便您找回密码以及使用短信验证码登录',
          inputs: [
            {
              name: 'mobile',
              placeholder: '手机号',
              checked: true,
              type: 'tel'
            },
          ],
          buttons: [
            {
              text: '确认',
              handler: (e) => {
                let pattern = /^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/;
                if (!pattern.test(e.mobile)) {
                  this.showToast("手机号码不合法，请确认是您本人的手机号")
                  return false;
                }
                this.user.changeMobile(e);
              }
            }
          ]
        });
        alert.present();
      }
    });
  }

  doRefresh(refresher) {
    console.log('Begin async operation', refresher);
    this.pages = [];
    this.params.page = 0;
    this.getPages();
    setTimeout(() => {
      refresher.complete();
    }, 500);
  }

  doInfinite(infiniteScroll) {
    this.params.page = this.params.page + 1;
    this.getPages()
    setTimeout(() => {
      infiniteScroll.complete();
    }, 1000);
  }

  getPages() {
    let reqParam = "?page=" + this.params.page + "&size=" + this.params.size + "&kindId=" + this.params.kind;
    let seq = this.api.get('plans' + reqParam).share();
    seq.subscribe((res: any) => {
      // If the API returned a successful response, mark the user as logged in
      if (res) {
        this.pages = this.pages.concat(res);
      } else {
        this.showToast(this.networkErrorString);
      }
    }, err => {
      this.showToast(this.networkErrorString);
      console.error('ERROR', err);
    });
    return seq;
  }

  getKinds() {
    let seq = this.api.get('kinds').share();
    seq.subscribe((res: any) => {
      // If the API returned a successful response, mark the user as logged in
      if (res) {
        this.kinds = res;
      } else {
        this.showToast(this.networkErrorString);
      }
    }, err => {
      this.showToast(this.networkErrorString);
      console.error('ERROR', err);
    });
    return seq;
  }

  openSearch() {
    let modal = this.modalController.create("SearchPage");
    modal.present();
  }

  openPages(url) {
    this.browser.launch(url);
  }

  showToast(msg) {
    return this.toastCtrl.create({
      message: msg,
      duration: 1000,
      position: 'top'
    }).present();
  }

  doRadio() {
    let alert = this.alerCtrl.create();
    alert.setSubTitle('选择彩种');
    alert.addInput({
      type: 'radio',
      label: '全部彩种',
      value: '0'
    });
    this.kinds.map((kind) => {
      alert.addInput({
        type: 'radio',
        label: kind.kind,
        value: kind.id
      });
    });
    alert.addButton({
      text: '确认',
      handler: data => {
        this.params.page = 0;
        if (data == -1) {
          this.currentKind = '全部彩种';
          this.params.kind = -1
        } else {
          this.kinds.forEach(value => {
            if (value.id === data) {
              this.currentKind = value.kind;
              this.params.kind = value.id
            }
          });
        }
        this.pages = [];
        this.getPages();
      }
    });
    alert.present();
  }

  openDetail(planDetail) {
    this.navCtrl.push('PlanDetailPage', planDetail);
  }
}
